#include <iostream>
#include <boost/asio.hpp>

using namespace boost::asio;
using namespace std;

io_service io;
serial_port port(io, "/dev/ttyUSB0");

int _usart_init__()
{
    try {
        // 设置串口参数
        port.set_option(serial_port_base::baud_rate(115200));
        port.set_option(serial_port_base::character_size(8));
        port.set_option(serial_port_base::parity(serial_port_base::parity::none)); // 修改设置为偶校验
        port.set_option(serial_port_base::stop_bits(serial_port_base::stop_bits::one));
        port.set_option(serial_port_base::flow_control(serial_port_base::flow_control::none));
    } catch (boost::system::system_error& e) {
        std::cerr << "Failed to initialize serial port: " << e.what() << std::endl;
        return -1;
    }
   
    return 0;
}

int _usart_send__(int arr[4])//串口发送函数
{
    try
    {
        io_service io;
        serial_port port(io, "/dev/ttyUSB0");

        // 将数组转换为字符串
        string data;
        for (int i = 0; i < 4; i++)
        {
            string tempdata=to_string(arr[i]);
            if (tempdata.length() < 3) 
            {
                tempdata = std::string(3 - tempdata.length(), '0') + tempdata;
            }

            // 添加到结果字符串中
            data += tempdata;

            if (i < 3){data += ",";}//加逗号分隔
            
        }
        cout<<data<<endl;
        write(port, buffer(data));

        return 0;
    }
    catch (std::exception& e)
    {
        // 处理异常情况
        std::cerr << "发送数据出错：" << e.what() << std::endl;
        return -1;
    }
}
    


